import React, { PureComponent } from 'react';
import { connect } from 'dva';
import myStyle from './index.less';
import { getUserInfo, isZiGuanEvir } from '../../../utils/commonFunc';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message } from 'antd';
import { TableC, DATA_ENTRY, AdvancedSearch, ContentPackage, PrimaryC } from '../../../comps';
import moment from 'moment';
import { showValue2 } from '../../PortfolioManagement/utils';
import AddRuleC from './addRule';
import dictData from './config';
@Form.create()
class LimitSetting extends PureComponent {
  state = {
    operateType: undefined, //新增 1 编辑 2
    record: undefined, //编辑某一行数据
    productList: [], //产品下拉
    NewcontrolValues: [],
    admin: undefined, //是否是管理员
    pageStatus: 1, //默认列表页1 新增/编辑 2
    currentPage: 1, //当前页码
    pageSize: 10, //每页数量
    isReset: false, //是否点击重置
  };

  componentDidMount() {
    const { dispatch } = this.props;
    //资管跳转过来的，要先请求getuser
    if (isZiGuanEvir()) {
      dispatch({
        type: 'dictionaryM/getUser', //获取用户信息
        payload: {
          userId: isZiGuanEvir() ? isZiGuanEvir()['iv-user'] : localStorage.getItem('antd-pro-userId'),
        },
        callback: (res) => {
          this.setState({
            admin: res.data.admin,
          });
          //获取表格列表
          this.setState(
            {
              currentPage: 1,
              numInPage: 10,
              isReset: false,
            },
            () => {
              this.getTableList();
            },
          );
        },
      });
    } else {
      //获取表格列表
      this.setState(
        {
          currentPage: 1,
          numInPage: 10,
          isReset: false,
        },
        () => {
          this.getTableList();
        },
      );
    }
    const {
      globalM: { dataDictionary },
    } = this.props;
    //进入页面，先查一下需要用到的字典吧
    dispatch({
      type: 'limitManagemen/save',
      payload: {
        dictMap: dataDictionary,
      },
    });
    //查询新增下的产品下拉
    dispatch({
      type: 'limitManagemen/fetchRootNode',
      payload: {
        createdBy: isZiGuanEvir() ? isZiGuanEvir()['iv-user'] : localStorage.getItem('antd-pro-userId'),
        due: 1,
      },
    }).then((res) => {
      if (res && res.code == 0) {
        const arr1 = res.data || [];
        let arr0 = [
          { value: 'ALL', title: '全选当前存续产品和新增产品' },
          { value: 'KFLC', title: '开放式理财产品' },
          { value: 'FBLC', title: '封闭式理财产品' },
          { value: 'XJGL', title: '现金管理类产品' },
          { value: 'GDSY', title: '固定收益类产品' },
          { value: 'GMLC', title: '公募理财产品' },
          { value: 'KFGMLC', title: '开放式公募理财产品' },
          { value: 'DKCP', title: '定开产品' },
          { value: 'OTHERKFSGMLCCP', title: '其他开放式公募理财产品' },
        ];
        let arr = arr0.concat(arr1);
        arr.map((item) => {
          if (['ALL', 'KFLC', 'FBLC', 'XJGL', 'GDSY', 'GMLC', 'KFGMLC', 'DKCP', 'OTHERKFSGMLCCP'].indexOf(item.value) < 0) item.title = item.value + '-' + item.title;
        });
        this.props.dispatch({
          type: 'limitManagemen/save',
          payload: {
            productList: arr,
          },
        });
      } else {
        this.props.dispatch({
          type: 'limitManagemen/save',
          payload: {
            productList: [],
          },
        });
      }
    });
    //列表查询条件的账户控制下拉
    this.combinFocus();
    //获取证券类型下拉
    this.getConditionDict();
  }
  componentWillUnmount() {
    //离开前清空缓存数据
    this.props.dispatch({
      type: 'limitManagemen/save',
      payload: {
        dictMap: {},
        productSelect: [],
        RootNode: [],
        productList: [],
        conditionOriginList: [],
      },
    });
  }
  //查询证券类型下拉 全部 用于分子的将证券类别名称 转化成列表结构
  getConditionDict = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'limitManagemen/queryConditionByIndexClass',
      payload: {},
    }).then((res) => {
      if (res && res.success && res.data) {
        let controlValues = []; //存储证券类别的下拉
        res.data.map((item) => {
          item.controlValues.map((item1) => {
            item1.boundName = item.boundName;
            controlValues.push(item1);
          });
        });
        let newData = this.setName([], controlValues); //将证券类别从树形结构转化成列表
        this.props.dispatch({
          type: 'limitManagemen/save',
          payload: {
            conditionOriginList: newData || [],
          },
        });
      }
    });
  };
  //将树形 转化为列表
  setName = (newControlValues, data) => {
    data.map((item) => {
      let newitem = {};
      newitem.value = item.value;
      newitem.boundName = item.boundName ? item.boundName : '债券wind分类';
      newitem.itemName = item.itemName;
      newitem.code = item.code;
      newControlValues.push(newitem);
      if (item.children && item.children.length > 0) {
        this.setName(newControlValues, item.children);
      }
    });
    return newControlValues;
  };
  //账户控制下拉
  combinFocus = () => {
    const {
      user: { currentUser },
    } = this.props;
    this.props.dispatch({
      type: 'limitManagemen/queryProduct',
      payload: {
        userId: isZiGuanEvir() ? isZiGuanEvir()['iv-user'] : localStorage.getItem('antd-pro-userId'),
      },
    });
  };
  //table点击编辑查看
  onEditItem = (item) => {
    const switchList = _.cloneDeep(dictData.switchList);
    let indexList = [];
    if (item && item.indexList) {
      indexList = item.indexList;
      this.setState({
        RiskIndexInfo: indexList,
      });
    }
    const record = item;
    for (var key in record) {
      //交易方向选中 回填
      switchList.map((item) => {
        if (item.value == key) {
          item.checked = record[key];
        }
      });
      if (key == 'controlValue') {
        //控制类别初始化 全部需要转换
        record[key] = this.formateData(record[key]);
      }
    }
    record.switchList = switchList;
    this.setState({
      operateType: 2,
      record: item,
      pageStatus: 2,
    });
  };
  //若选中项为全部，初始化全部数据选中
  formateData = (val) => {
    const {
      limitManagemen: { productList },
    } = this.props;
    let arr;
    if (val) {
      const all = val.filter((item) => item == 'ALL');
      if (all && all.length) {
        productList.map((item) => {
          if (item.value !== 'ALL') item.disabled = true;
        });
        this.props.dispatch({
          type: 'limitManagemen/save',
          payload: {
            productList: productList,
          },
        });
      } else {
        productList.map((item) => {
          if (item.value !== 'ALL') item.disabled = false;
        });
        this.props.dispatch({
          type: 'limitManagemen/save',
          payload: {
            productList: productList,
          },
        });
      }
      return all && all.length ? ['ALL'] : val;
    }
  };
  //获取限额设置列表
  getTableList = () => {
    const { dispatch } = this.props;
    const { pageSize, currentPage, isReset } = this.state;
    const params = this.state.searchRef.props.form.getFieldsValue();
    const value = {
      productCodeList: params.search_productCodeList,
      ruleDesc: params.search_ruleDesc,
      ruleApplyObjs: params.search_ruleApplyObj,
      pageNumber: currentPage,
      pageSize,
      // tenant: !isZiGuanEvir() ? localStorage.getItem('antd-pro-tenant') : sessionStorage.getItem("maat-antd-pro-tenant"),
    };
    if (isReset) {
      message.warning('您已重置查询字段，请设置条件后执行查询');
      return;
    }
    dispatch({
      type: 'limitManagemen/fetch',
      payload: value,
    });
  };
  //table点击删除
  onDeleteItem = (id) => {
    const {
      dispatch,
      limitManagemen: { pagination },
    } = this.props;
    dispatch({
      type: 'limitManagemen/deleteRule',
      payload: {
        ruleId: id,
        tenant: !isZiGuanEvir() ? localStorage.getItem('antd-pro-tenant') : sessionStorage.getItem('maat-antd-pro-tenant'),
      },
    }).then((response) => {
      if (response) {
        this.setState(
          {
            currentPage: 1,
            pageSize: 10,
            isReset: false,
          },
          () => {
            this.getTableList();
          },
        );
      }
    });
  };

  //table分页
  onTableChange = (pagination) => {
    const { current, pageSize } = pagination;
    this.setState(
      {
        currentPage: current,
        pageSize: pageSize,
      },
      () => {
        this.getTableList();
      },
    );
  };

  //点击新建
  handleAddCurb = () => {
    this.setState({
      operateType: 1,
      record: undefined, //新增时 选中行清空
      pageStatus: 2,
    });
  };
  //根据value查找title
  findTitleByValue = (type, val) => {
    let text = '--';
    dictData[type].map((item) => {
      if (item.value == val) text = item.title;
    });
    return text;
  };
  //渲染表格
  renderCurbTable() {
    const {
      limitManagemen: { list, pagination, dictMap, columns: columnsProps },
      loading,
    } = this.props;
    const columns = _.cloneDeep(columnsProps);
    columns.map((item, key) => {
      if (item.key == 'ruleCategory') {
        item.render = (val) => <span>{val !== null ? showValue2('risk_category', dictMap, val.toString()) : '--'}</span>;
      }
      if (item.key == 'ruleDesc') {
        item.ellipsis = true;
      }
      if (item.key != 'ruleDesc' && item.key != 'operate') {
        item.width = 80;
        if (item.key == 'effectiveTime' || item.key == 'expireTime') {
          item.width = 110;
        }
      }
      if (item.key == 'ruleApplyObj') {
        item.render = (text, record) => {
          return this.findTitleByValue('applyObj', text);
        };
      }
      if (item.key == 'ruleState') {
        item.render = (text, record) => {
          return this.findTitleByValue('falseOrTrue', text);
        };
      }
      if (item.key == 'compareMethod') {
        item.render = (val) => <span>{val !== null ? showValue2('risk_value_compare_method', dictMap, val.toString()) : '--'}</span>;
      }
      if (item.key == 'effectiveTime' || item.key == 'expireTime') {
        item.render = (val) => <span>{val ? moment(val).format('YYYY-MM-DD') : '--'}</span>;
      }
    });
    if (this.isAdmin() && columns.length && columns[columns.length - 1].key != 'operate') {
      let item = {};
      item.width = 110;
      item.type = 'operate';
      item.title = '操作';
      item.dataIndex = 'operate';
      item.key = 'operate';
      item.operates = [
        {
          title: '编辑',
          onClick: (record, index) => this.onEditItem(record),
        },
        {
          title: '删除',
          onClick: (record, index) => this.onDeleteItem(record.ruleId),
        },
      ];
      columns.push(item);
    }
    return (
      <div>
        <TableC
          columns={columns}
          dataSource={list ? list.data : []}
          onChange={this.onTableChange}
          rowKey='ruleId'
          loading={loading.effects[`limitManagemen/fetch`] == true}
          current={this.state.currentPage}
          total={pagination && pagination.total}
          pageSize={this.state.pageSize}
          selfScrollY={true}
        />
      </div>
    );
  }
  //判断是否是管理员
  isAdmin = () => {
    const { admin } = this.state;
    let temp = isZiGuanEvir() ? admin : getUserInfo().isTenantAdmin;
    return temp;
  };
  //修改账户控制的值
  changeProduct = (obj) => {
    let data = [];
    obj.map((item) => {
      data.push({
        title: item.portfolioCode + '-' + item.portfolioName,
        value: item.portfolioCode,
      });
    });
    return data;
  };
  //搜索栏
  renderForm() {
    const {
      limitManagemen: { productSelect },
      form: { resetFields },
      dispatch,
    } = this.props;
    const productObj = this.changeProduct(productSelect);
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'search_ruleDesc',
          title: '风险说明',
          type: DATA_ENTRY.INPUT,
        },
        {
          dataIndex: 'search_ruleApplyObj',
          title: '作用范围',
          type: DATA_ENTRY.SELECT,
          dataSource: dictData.applyObj,
          allowClear: true,
          isMultiple: true,
        },
        {
          dataIndex: 'search_productCodeList',
          title: '账户控制',
          type: DATA_ENTRY.SELECT,
          dataSource: productObj,
          isMultiple: true,
          allowClear: true,
        },
      ],
      onRef: (ref) => {
        this.state.searchRef = ref;
      },
      onQuery: (e) => {
        this.setState(
          {
            currentPage: 1,
            pageSize: 10,
            isReset: false,
          },
          () => {
            this.getTableList();
          },
        );
      },
      onClear: () => {
        this.setState({
          isReset: true,
        });
      },
    };
    return (
      <div style={{ marginBottom: '15px' }}>
        <AdvancedSearch {...searchProps} />
      </div>
    );
  }
  //子页面点击了 取消
  onCancle = () => {
    const {
      limitManagemen: { productList },
    } = this.props;
    this.setState({
      pageStatus: 1,
      record: undefined,
      operateType: undefined,
    });
    productList.map((item) => {
      if (item.value !== 'ALL') item.disabled = false;
    });
    this.props.dispatch({
      type: 'limitManagemen/save',
      payload: {
        productList: productList,
      },
    });
    console.log('取消');
  };
  //子页面点击了 确定 刷新列表
  onOk = () => {
    this.setState(
      {
        pageStatus: 1,
        currentPage: 1,
        numInPage: 10,
        isReset: false,
        record: undefined,
        operateType: undefined,
      },
      () => {
        this.getTableList();
      },
    );
  };
  //分子分母变 修改detailData
  changeDetailData = (indexList = []) => {
    const { record = {} } = this.state;
    record.indexList = [...indexList];
    this.setState({
      record: { ...record },
    });
  };
  render() {
    const { pageStatus, record, operateType } = this.state;
    return (
      <ContentPackage
        title='限额管理'
        contentHtml={
          <div>
            <div style={{ display: pageStatus == 1 ? 'inherit' : 'none' }}>
              {this.renderForm()}
              {this.isAdmin() && <PrimaryC title='新增' style={{ marginBottom: '10px' }} onClick={() => this.handleAddCurb()} />}
              {this.renderCurbTable()}
            </div>
            {pageStatus == 2 && <AddRuleC detailData={record} type={operateType} onCancle={this.onCancle} onOk={this.onOk} changeDetailData={this.changeDetailData} />}
          </div>
        }
      />
    );
  }
}

export default connect(({ limitManagemen, dictionaryM, userM: user, loading, globalM }) => ({
  limitManagemen,
  dictionaryM,
  user,
  loading,
  globalM,
}))(LimitSetting);
